package com.itheima.reggie.controller;

import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Address;
import com.itheima.reggie.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
public class AddressController {

    @Autowired
    private AddressService addressService;

    //查询我的地址列表
    @GetMapping("/address/list")
    public ResultInfo findList() {
        List<Address> list = addressService.findList();
        return ResultInfo.success(list);
    }

    //添加收获地址
    @PostMapping("/address")
    public ResultInfo add(@RequestBody Address address) {
        addressService.add(address);
        return ResultInfo.success(null);
    }

    //设置默认地址
    @PutMapping("/address/default")
    public ResultInfo setdefault(@RequestBody Map<String, Long> map) {
        //1.接收参数
        Long id = map.get("id");
        //2.设置默认地址
        addressService.setdefault(id);
        //3.返回结果
        return ResultInfo.success(null);
    }

    //查询当前用户的默认地址
    @GetMapping("/address/default")
    public ResultInfo findDefault() {
        //1.查询默认地址
        Address address = addressService.findDefault();
        //2.根据返回的地址进行判断
        if (address == null) {
            //3.没有设置默认地址
            return ResultInfo.error("没有设置默认地址");
        } else {
            //4.已设置默认地址
            return ResultInfo.success(address);
        }
    }

    //根据主键查询收货地址（数据回显）
    @GetMapping("/address/{id}")
    public ResultInfo findById(@PathVariable("id") Long id) {
        Address address = addressService.findById(id);
        return ResultInfo.success(address);
    }

    //修改收货地址
    @PutMapping("/address")
    public ResultInfo update(@RequestBody Address address) {
        addressService.update(address);
        return ResultInfo.success(null);
    }

    //删除收货地址
    @DeleteMapping("/address")
    public ResultInfo deleteByIds(long[] ids) {
        if (ids != null && ids.length > 0) {
            addressService.deleteByIds(ids);
        }
        return ResultInfo.success(null);
    }
}
